package com.mybatis.lo.executor;

import com.mybatis.lo.config.Configuration;
import com.mybatis.lo.config.MappedStatement;
import com.mybatis.lo.handler.StatementHandler;
import com.mybatis.lo.mapping.BoundSql;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

/**
 * 简单Statement执行器，维护简单的查询流程：
 * 1.获取连接；
 * 2.获取StatementHandler；
 * 3.获得预处理器；
 * 4.设置参数；
 * 5.请求并返回结果；
 * 6.释放资源
 * @author zhangbh
 * 2023-06-19 08:32
 **/
public class SimpleExecutor extends BaseExecutor {
    @Override
    protected <T> List<T> queryFromDatabases(MappedStatement mappedStatement, Configuration configuration, Object param) {

        BoundSql boundSql = mappedStatement.getBoundSql(param);
        Statement statement = null;
        Connection connection = null;
        try {
            // 1、获取连接
            connection = configuration.getDataSource().getConnection();
            // 2、从配置中心获取对应的StatementHandler
            StatementHandler statementHandler = configuration.newStatementHandler(mappedStatement, boundSql, param);
            // 3、获得预处理器
            statement = statementHandler.prepare(connection);
            // 4、设置参数
            statementHandler.parameterize(statement);
            // 5、请求并返回结果
            return statementHandler.query(statement);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("数据库查询出现异常");
        } finally {
            // 6、释放资源
            releaseConnection(connection, statement);
        }
        return null;
    }

    private void releaseConnection(Connection connection, Statement statement) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                // ignore
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (Exception e) {
                // ignore
            }
        }
    }
}
